package com.example.controller;

import com.example.domain.Comment;
import com.example.domain.Post;
import com.example.domain.User;
import com.example.service.CommentService;
import com.example.service.PostService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Pattern;
//处理用户注册、登录、注销、修改密码等功能
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PostService postService;

    @Autowired
    private CommentService commentService;

    // 显示登录页面（GET 请求）
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showLoginPage() {
        return "login";
    }

    // 处理登录逻辑（POST 请求）
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, HttpServletRequest request) {
        try {
            User u = userService.login(user);
            if (u != null) {
                request.getSession().setAttribute("USER_SESSION", u);
                return "redirect:/main"; // 修改为重定向
            }
            request.setAttribute("msg", "用户名或密码错误");
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "login";
        }
    }

    // 用户注册
    @RequestMapping("/register")
    public String register(User user, HttpServletRequest request) {
        try {
            // 验证密码强度
            if (!isValidPassword(user.getPassword())) {
                request.setAttribute("msg", "密码不符合要求：至少8位，包含英文字母、数字和特殊字符");
                return "register";
            }

            userService.register(user);
            request.setAttribute("msg", "注册成功，请登录");
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "注册失败");
            return "register";
        }
    }

    // 用户注销 - 移除了与AdminController冲突的admin/logout映射
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();
        }
        return "login"; // 注销后跳回登录页
    }

    // 用户个人资料页面
    @RequestMapping("/user/profile")
    public String userProfile(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        if (user == null) {
            return "redirect:/login";
        }

        List<Post> myPosts = postService.findByUserId(user.getId());
        List<Comment> myComments = commentService.findByUserId(user.getId());

        request.setAttribute("myPosts", myPosts);
        request.setAttribute("myComments", myComments);

        return "userProfile";
    }

    // 显示修改密码页面
    @RequestMapping(value = "/user/changePassword", method = RequestMethod.GET)
    public String showChangePasswordPage(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        if (user == null) {
            return "redirect:/login";
        }
        return "changePassword";
    }

    // 处理修改密码请求
    @RequestMapping(value = "/user/changePassword", method = RequestMethod.POST)
    public String changePassword(
            @RequestParam("currentPassword") String currentPassword,
            @RequestParam("newPassword") String newPassword,
            @RequestParam("confirmPassword") String confirmPassword,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");

        if (user == null) {
            return "redirect:/login";
        }

        try {
            // 验证当前密码
            if (!user.getPassword().equals(currentPassword)) {
                request.setAttribute("msg", "当前密码错误");
                request.setAttribute("msgType", "error");
                return "changePassword";
            }

            // 验证新密码和确认密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                request.setAttribute("msg", "两次输入的新密码不一致");
                request.setAttribute("msgType", "error");
                return "changePassword";
            }

            // 验证新密码强度
            if (!isValidPassword(newPassword)) {
                request.setAttribute("msg", "新密码不符合要求：至少8位，包含英文字母、数字和特殊字符");
                request.setAttribute("msgType", "error");
                return "changePassword";
            }

            // 检查新密码是否与当前密码相同
            if (currentPassword.equals(newPassword)) {
                request.setAttribute("msg", "新密码不能与当前密码相同");
                request.setAttribute("msgType", "error");
                return "changePassword";
            }

            // 更新密码
            userService.updatePassword(user.getId(), newPassword);

            // 更新session中的用户信息
            user.setPassword(newPassword);
            session.setAttribute("USER_SESSION", user);

            request.setAttribute("msg", "密码修改成功！");
            request.setAttribute("msgType", "success");
            return "changePassword";

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误，密码修改失败");
            request.setAttribute("msgType", "error");
            return "changePassword";
        }
    }

    // 密码强度验证方法
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }

        // 检查是否包含英文字母
        boolean hasLetter = Pattern.compile("[a-zA-Z]").matcher(password).find();

        // 检查是否包含数字
        boolean hasNumber = Pattern.compile("\\d").matcher(password).find();

        // 检查是否���含特殊字符
        boolean hasSpecial = Pattern.compile("[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]").matcher(password).find();

        return hasLetter && hasNumber && hasSpecial;
    }

    // 测试接口
    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "Spring Controller is working!";
    }
}
